package com.zj;

import com.google.gson.Gson;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class BankTask implements Runnable{
    private Socket socket;
    private Bank b;
    private boolean flag;
    public BankTask(Socket socket,Bank b){
        this.socket=socket;
        this.b=b;
        this.flag=true;
    }

    @Override
    public void run() {
        try(
                //因为要用到try...resource 直接关闭socket 所以需要将socket 重新在try注册
                Socket s=this.socket;
                Scanner reader=new Scanner(s.getInputStream());
                PrintWriter writer=new PrintWriter(s.getOutputStream());  //包装成字符流
        ){
            //线程中止判断 flag业务中止判断  Thread.currentThread().isInterrupted() 线程中止判断
            while(flag && !Thread.currentThread().isInterrupted()){
                //客户端是否没有传数据,如没有传,则结束
                if(!reader.hasNext()){
                    System.out.println("客户端"+s.getRemoteSocketAddress()+"断开连接");
                    break;
                }
                //如果有数据,则读取
                String command=reader.next();  //取第一部分  DEPOSIT 1 100  取出 DEPOSIT
                BankAccount ba=null;
                JsonModel<BankAccount> jm=new JsonModel<>();
                //命令模式 :
                if ("DEPOSIT".equalsIgnoreCase(command)){
                    //存款
                    int id=reader.nextInt();
                    double money=reader.nextDouble();
                    ba=b.deposit(id,money);
                }else if("WITHDRAW".equalsIgnoreCase(command)){
                    //取款
                    int id=reader.nextInt();
                    double money=reader.nextDouble();
                    ba=b.withdraw(id,money);
                }else if("BALANCE".equalsIgnoreCase(command)){
                    //查询余额
                    int id=reader.nextInt();
                    ba=b.search(id);
                }else if("QUIT".equalsIgnoreCase(command)){
                    //断开连接
                    System.out.println("atm客户端要求主动断开"+s.getRemoteSocketAddress());
                    break;
                }else {
                    jm.setCode(0);
                    jm.setErrorMsg("命令错误");

                    Gson g=new Gson();
                    String jsonString=g.toJson(jm);
                    writer.println(jsonString);
                    writer.flush();
                    continue;
                }
                //将基本字符串转换为json字符串
                jm.setCode(1);
                jm.setObj(ba);

                Gson g=new Gson();
                String jsonString=g.toJson(jm);
                writer.println(jsonString);
                writer.flush();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
